<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="标题" prop="title">
                <el-input v-model="queryParams.title" placeholder="请输入标题" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item label="详情介绍" prop="articleTitle">
                <el-input v-model="queryParams.articleTitle" placeholder="请输入详情介绍" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <!-- 添加状态值查询条件 -->
            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @change="handleQuery">
                    <el-option label="上线" value="1"></el-option>
                    <el-option label="删除" value="-1"></el-option>
                    <el-option label="未上线" value="0"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['cms:action:add']">新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['cms:action:edit']">修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDeleteBatch" v-hasPermi="['cms:action:remove']">删除
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="actionList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" :selectable="checkSelectable" />
            <!-- <el-table-column label="" align="center" prop="id" /> -->
            <!-- <el-table-column label="标题" align="center" prop="title" /> -->
            <!-- <el-table-column label="详情介绍" align="center" prop="articleTitle" /> -->
            <el-table-column label="图片" align="center" prop="image" width="100">
                <template slot-scope="scope">
                    <image-preview :src="scope.row.image" :width="50" :height="50" />
                </template>
            </el-table-column>
            <!-- 合并标题和详情介绍 -->
            <el-table-column label="标题/详情介绍" align="center" width="200">
                <template slot-scope="scope">
                    <div>
                        <div class="text-ellipsis" :title="scope.row.title || ''">
                            {{ scope.row.title }}
                        </div>
                        <div class="text-ellipsis desc-text" :title="scope.row.articleTitle || ''">
                            {{ scope.row.articleTitle }}
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="排序" align="center" prop="sort" />
            <!-- <el-table-column label="url地址" align="center" prop="url" /> -->
            <el-table-column label="开始时间" align="center" prop="startTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.startTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="结束时间" align="center" prop="endTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.endTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态值" align="center" prop="status">
                <template slot-scope="scope">
                    <span v-if="scope.row.status === 1">上线</span>
                    <span v-else-if="scope.row.status === -1">删除</span>
                    <span v-else-if="scope.row.status === 0">未上线</span>
                    <span v-else>--</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['cms:action:edit']" v-if="scope.row.status !== -1">修改
                    </el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['cms:action:remove']" v-if="scope.row.status !== -1">删除
                    </el-button>
                    <!-- 新增状态更新按钮 -->
                    <el-dropdown v-if="scope.row.status !== -1" size="mini" @command="(command) => handleUpdateStatus(scope.row, command)">
                        <el-button size="mini" type="text">
                            更改状态<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item :command="1" :disabled="scope.row.status === 1">上线</el-dropdown-item>
                            <el-dropdown-item :command="0" :disabled="scope.row.status === 0">未上线</el-dropdown-item>
                            <el-dropdown-item :command="-1" :disabled="scope.row.status === -1">删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 添加或修改轮播广告对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入标题" />
                </el-form-item>
                <el-form-item label="详情介绍" prop="articleTitle">
                    <el-input v-model="form.articleTitle" placeholder="请输入详情介绍" />
                </el-form-item>
                <el-form-item label="图片" prop="image">
                    <image-upload v-model="form.image" />
                </el-form-item>
                <!-- <el-form-item label="url地址" prop="url">
                    <el-input v-model="form.url" type="textarea" placeholder="请输入内容" />
                </el-form-item> -->
                <el-form-item label="排序" prop="sort">
                    <el-input v-model="form.sort" placeholder="请输入排序" />
                </el-form-item>
                
                <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker clearable v-model="form.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择开始时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker clearable v-model="form.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择结束时间">
                    </el-date-picker>
                </el-form-item>
                <!-- 添加状态选择 -->
                <el-form-item label="状态" prop="status">
                    <el-select v-model="form.status" placeholder="请选择状态">
                        <el-option label="上线" :value="1"></el-option>
                        <el-option label="未上线" :value="0"></el-option>
                        <el-option label="删除" :value="-1"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getAction, listAction, addAction, updateAction, delAction, batchDelAction } from "@/api/cms/loop-action"

export default {
    name: "Action",
    data() {
        // 验证结束时间不能小于开始时间
        var validateEndTime = (rule, value, callback) => {
            if (this.form.startTime && this.form.endTime) {
                const startTime = new Date(this.form.startTime).getTime();
                const endTime = new Date(this.form.endTime).getTime();
                if (endTime < startTime) {
                    callback(new Error('结束时间不能小于开始时间'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };
        
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 轮播广告表格数据
            actionList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                title: null,
                image: null,
                url: null,
                sort: null,
                articleTitle: null,
                startTime: null,
                endTime: null,
                status: "1"  // 查询时默认不设置状态筛选
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
                image: [{ required: true, message: "图片不能为空", trigger: "blur" }],
                status: [{ required: true, message: "状态不能为空", trigger: "change" }],
                endTime: [{ validator: validateEndTime, trigger: "change" }]
            }
        }
    },
    created() {
        this.getList()
    },
    methods: {
        /** 查询轮播广告列表 */
        getList() {
            this.loading = true
            listAction(this.queryParams).then(response => {
                this.actionList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                title: null,
                image: null,
                url: null,
                sort: null,
                articleTitle: null,
                startTime: null,
                endTime: null,
                status: 1 // 默认状态为上线
            }
            this.resetForm("form")
        },
        // 检查行是否可选
        checkSelectable(row, index) {
            // 状态为删除(-1)的行不可选
            return row.status !== -1;
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm")
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = "添加轮播广告"
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getAction(id).then(response => {
                this.form = response.data
                this.open = true
                this.title = "修改轮播广告"
            })
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    // 添加时间验证判断
                    if (this.form.startTime && this.form.endTime) {
                        const startTime = new Date(this.form.startTime).getTime();
                        const endTime = new Date(this.form.endTime).getTime();
                        if (endTime < startTime) {
                            this.$modal.msgError("结束时间不能小于开始时间");
                            return;
                        }
                    }
                    
                    if (this.form.id != undefined) {
                        updateAction(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功")
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addAction(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功")
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            // 如果传入了row参数，则是单个删除
            if (row) {
                this.$modal.confirm('是否确认删除名称为"' + row.title + '"的数据项？').then(() => {
                    return delAction(row.id)
                }).then(() => {
                    this.getList()
                    this.$modal.msgSuccess("删除成功")
                }).catch(() => { 
                    this.$modal.msgError("删除失败")
                })
            } else {
                // 调用批量删除方法
                this.handleDeleteBatch()
            }
        },

        handleDeleteBatch() {
            // 批量删除
            const actionIds = this.ids
            this.$modal.confirm('是否确认删除选中的数据项？').then(() => {
                // 使用优化后的delAction接口，直接传入id数组进行批量删除
                return batchDelAction(actionIds)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess("删除成功")
            }).catch(() => {
                this.$modal.msgError("删除失败")
            })
        },
        // 新增状态更新按钮操作
        handleUpdateStatus(row, status) {
            // 创建一个包含id和status的对象
            const updateData = {
                id: row.id,
                status: status
            }
            
            // 调用更新状态接口
            updateAction(updateData).then(response => {
                this.$modal.msgSuccess("状态更新成功")
                this.getList()
            }).catch(() => {
                this.$modal.msgError("状态更新失败")
            })
        }
    }
}
</script>
<style scoped>
.text-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.desc-text {
    color: #999;
}
</style>
